<template>
  <div class="app-container">
    <div class="space">
      <el-form
        v-show="showSearch"
        ref="queryForm"
        :model="queryParams"
        size="small"
        :inline="true"
      >
        <el-form-item label="名称" prop="search">
          <el-input
            v-model="queryParams.search"
            placeholder="通过用户ID、昵称、创建人进行模糊搜索"
            clearable
            style="width: 310px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="修改时间" prop="signTime">
          <el-date-picker
            v-model="queryParams.signTime"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"
            >查询</el-button
          >
          <el-button icon="el-icon-refresh" class="delBtn" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            v-if="addMenu"
            >新增用户</el-button
          >
        </el-col>
      </el-row>
    </div>
    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :show-search.sync="showSearch"
        :columns="columns"
        @queryTable="getListData"
      />
    </el-row>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="loading"
      :data="roleList"
      style="margin-top: 20px"
    >
      <el-table-column
        v-if="columns[0].visible"
        key="id"
        label="用户ID"
        prop="id"
        :show-overflow-tooltip="true"
        align="left"
      />
      <el-table-column
        v-if="columns[1].visible"
        key="name"
        label="用户昵称"
        prop="name"
        :show-overflow-tooltip="true"
        align="left"
      />
      <el-table-column
        v-if="columns[2].visible"
        key="optName"
        label="创建人"
        prop="optName"
        :show-overflow-tooltip="true"
        align="left"
      />
      <el-table-column
        v-if="columns[3].visible"
        key="roleName"
        label="所属角色"
        prop="roleName"
        :show-overflow-tooltip="true"
        align="left"
      >
      </el-table-column>
      <el-table-column
        v-if="columns[4].visible"
        key="createTime"
        label="启用状态"
        align="left"
        prop="createTime"
      >
        <template slot-scope="scope">
          <div class="flex_box">
            <p>启用</p>
            <el-switch
              v-model="scope.row.status == 1"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="changeStatus(scope.row)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns[5].visible"
        key="updateTime"
        label="最新修改时间"
        align="left"
        prop="updateTime"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) || "--" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="left"
        fixed="right"
        class-name="fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            class="btnText"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="updateMenu"
            >修改</el-button
          >
          <el-button
            class="btnText"
            type="text"
            @click="handleDel(scope.row)"
            v-if="updateMenu"
            >删除</el-button
          >
          <el-button
            type="text"
            class="btnText"
            v-if="resetMenu"
            @click="handleDelete(scope.row)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getListData"
    />
    <el-dialog :title="title" :visible.sync="open" width="786px" append-to-body>
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="用户昵称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="支持中文、数字、字母"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="登录账号" prop="loginAcc">
          <el-input
            v-model="addForm.loginAcc"
            @input="handleInput"
            :disabled="addForm.id ? true : false"
            placeholder="支持数字、字母、推荐使用手机号"
          />
        </el-form-item>
        <el-form-item label="所属角色" prop="jobId">
          <el-select
            v-model="addForm.jobId"
            placeholder="请选择角色"
            class="w-100"
          >
            <el-option
              v-for="item in addOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <p class="ts"><span>! </span>账号初始密码为啊a123456</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" class="add" @click="submitForm">{{
          addForm.id ? "确认修改" : "确认新增"
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, handUser, delUser } from "@/api/index";
import { listRole } from "@/api/system/role";
import { mapGetters } from "vuex";
export default {
  name: "ShopManage",
  computed: {
    ...mapGetters(["menuIds"]),
    addMenu() {
      return this.menuIds.includes("4001");
    },
    updateMenu() {
      return this.menuIds.includes("4002");
    },
    resetMenu() {
      return this.menuIds.includes("4003");
    },
  },
  data() {
    return {
      row: {},
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      addOption: [],
      open: false,
      columns: [
        { key: 0, label: `用户ID`, visible: true },
        { key: 1, label: `用户昵称`, visible: true },
        { key: 2, label: `创建人`, visible: true },
        { key: 3, label: `所属角色`, visible: true },
        { key: 4, label: `启用状态`, visible: true },
        { key: 5, label: `最新修改时间`, visible: true },
      ],
      title: "新增",
      tableKey: 0,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 10,
      // 角色表格数据
      roleList: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        search: "",
        status: "",
        signTime: "",
      },
      // 表单参数
      form: {},
      addForm: {
        type: 3,
        name: "",
        loginAcc: "",
        jobId: "",
      },
      addRules: {
        name: [{ required: true, message: "内容不能为空", trigger: "blur" }],
        jobId: [{ required: true, message: "内容不能为空", trigger: "change" }],
        loginAcc: [
          { required: true, message: "内容不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getListData();
    listRole({ current: 1, size: 500 }).then((res) => {
      if (res.data.records.length) {
        this.addOption = res.data.records.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      }
    });
  },
  methods: {
    handleInput(value) {
      // 替换掉所有中文字符
      this.addForm.loginAcc = value.replace(/[\u4e00-\u9fa5]+/g, "");
    },
    /** 删除按钮操作 */
    handleDel(row) {
      let roleIds = row.id;
      if (Array.isArray(roleIds)) {
        roleIds = roleIds.join(",");
      }
      this.$modal
        .confirm("是否删除该用户吗？")
        .then(() => {
          return delUser({
            id: roleIds,
          });
        })
        .then(() => {
          this.getListData();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },
    changeStatus(row) {
      console.log(row);
      this.$modal
        .confirm(`确定要${row.status == 1 ? "停用" : "启用"}该用户吗？`)
        .then(() => {
          return handUser({
            id: row.id,
            status: row.status == 1 ? 0 : 1,
          });
        })
        .then(() => {
          if (row.id == localStorage.getItem("userId") && row.status == 1) {
            this.$modal.msgError("该登录账号已停用,请重新登录!");
            setTimeout(() => {
              this.$store.dispatch("LogOut").then(() => {
                // location.href = "/login";
                this.$router.push("/login");
              });
            }, 1500);
          } else {
            row.status = row.status == 1 ? 0 : 1;
            this.$modal.msgSuccess("操作成功");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    reset() {
      this.addForm = {
        type: 3,
        name: "",
        loginAcc: "",
        jobId: "",
      };
      this.resetForm("addForm");
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    handleUpdate(row) {
      this.reset();
      this.title = "修改用户";
      this.addForm.id = row.id;
      this.addForm.name = row.name;
      this.addForm.loginAcc = row.loginAcc;
      this.addForm.jobId = row.jobId;
      this.open = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("确定要重置该账号的密码吗？")
        .then(() => {
          return handUser({
            id: row.id,
            password: "a123456",
          });
        })
        .then(() => {
          if (row.id == localStorage.getItem("userId")) {
            this.$modal.msgError("该登录账号密码已重置,请重新登录!");
            setTimeout(() => {
              this.$store.dispatch("LogOut").then(() => {
                // location.href = "/login";
                this.$router.push("/login");
              });
            }, 1500);
          } else {
            this.$modal.msgSuccess("操作成功");
          }
        })
        .catch(() => {});
    },
    handleAdd() {
      this.title = "新增用户";
      this.open = true;
      this.reset();
    },
    /** 查询角色列表 */
    getListData() {
      const data = {
        ...this.queryParams,
        startTime:
          this.queryParams.signTime &&
          new Date(this.queryParams.signTime[0]).getTime(),
        endTime:
          this.queryParams.signTime &&
          new Date(this.queryParams.signTime[1]).getTime(),
        type: 3,
        source: 2,
      };
      delete data.signTime;
      getRoleList(data).then((response) => {
        this.roleList = response.data.records || [];
        this.total = response.data.total || 0;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$nextTick(() => {
        this.queryParams.current = 1;
        this.getListData();
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.current = 1;
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          handUser({
            ...this.addForm,
            password: "a123456",
            optId: localStorage.getItem("userId"),
          }).then((response) => {
            this.$modal.msgSuccess(this.addForm.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getListData();
          });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.ts {
  font-size: 16px;
  color: #333;
  padding-left: 24px;
  span {
    color: red;
  }
}
.w-100 {
  width: 100%;
}
.flex_box {
  display: flex;
  align-items: center;
  gap: 5px;
}
.btnText {
  color: #0052d9 !important;
}
.dialogForm {
  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
  ::v-deep.el-form--label-top .el-form-item__label {
    padding: 0;
  }
}
.add {
  background: #0052d9;
  color: #fff;
  border: none;
}
.delBtn {
  background: #e7e7e7;
  color: #000;
  border: none;
}
.open {
  width: 52px;
  height: 32px;
  background: #e3f9e9;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #2ba471;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 400;
  font-size: 14px;
  color: #2ba471;
}
.close {
  width: 52px;
  height: 32px;
  background: #d8d8d8;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #767676;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 400;
  font-size: 14px;
  color: #767676;
}
.statusBox {
  width: 100%;
  display: flex;
  justify-content: center;
}
.img {
  width: 38px;
  height: 38px;
}
</style>
